package org.dgm.nw.core.viewControl.model;

import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.dgm.nw.core.viewControl.ActionMappingParse;
import org.dom4j.Document;
import org.dom4j.Element;

/**
 * 请求url所对应的 类路径 和方法名。
 * 根据strPathInfo 得到 此对象，
 * 
 * Copyright asiainf-linkage Corporation 2013
 */
public class ActionInstance {

	Logger log = Logger.getLogger(this.getClass());

	/**
	 * 类路径
	 */
	private String actionPath;

	/**
	 * 方法名
	 */
	private String methodName;

	public String getActionPath() {
		return actionPath;
	}

	public void setActionPath(String actionPath) {
		this.actionPath = actionPath;
	}

	public String getMethodName() {
		return methodName;
	}

	public void setMethodName(String methodName) {
		this.methodName = methodName;
	}

	public ActionInstance(String strPathInfo) throws Exception {
		Element rootEle = ActionMappingParse.getInstance().getRootElm();
		Map packageMap = ActionMappingParse.generateChildrenElementMapByColumn(
				rootEle, "namespace");
		log.info(packageMap);

		Set<String> namespaceSet = packageMap.keySet();
		int matchLength = 0;
		String matchnamespace = "";
		for (String namespace : namespaceSet) {
			if (strPathInfo.startsWith(namespace)) {
				int currentMatchLength = namespace.length();
				// 相当于更匹配
				if (currentMatchLength > matchLength) {
					matchLength = currentMatchLength;
					matchnamespace = namespace;
				}
			}
		}
		if (matchnamespace.equals("")) {
			throw new Exception("没有匹配的namespace");
		}
		Element packageElement = (Element) packageMap.get(matchnamespace);

		// 去掉前缀，找到action中
		String actionName = strPathInfo.substring(matchLength + 1);
		Map actionMap = ActionMappingParse.generateChildrenElementMapByColumn(
				packageElement, "name");
		Set<String> actionNameSet = actionMap.keySet();

		// 得到actionElement
		Element actionElement = null;
		for (String name : actionNameSet) {
			if (name.equals(actionName)) {
				actionElement = (Element) actionMap.get(actionName);
				break;
			}
		}

		if (actionElement == null) {
			throw new Exception("没有对应的actionElement");
		}

		this.setActionPath(actionElement.attributeValue("class"));
		this.setMethodName(actionElement.attributeValue("method"));
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "actionPath:" + actionPath + "," + "methodName:" + methodName;
	}

}
